package com.qiall.boot.userservice.Impl.organization.activity;

import com.qiall.assertutil.Assert;
import com.qiall.boot.userservice.data.mapper.OrganizationInfoMapper;
import com.qiall.common.exception.BusinessException;
import com.qiall.common.exception.ResultCode;
import com.qiall.common.request.BaseActivity;
import com.qiall.common.request.BaseResponse;
import com.qiall.common.request.GetByIdRequest;
import com.qiall.user.ability.entity.AddOrganizationDTO;
import com.qiall.user.ability.entity.IsAdminDTO;
import com.qiall.user.ability.entity.OrganizationResponse;
import com.qiall.user.ability.entity.UserInfoDTO;
import com.qiall.user.ability.service.organization.OrganizationService;
import com.qiall.user.ability.service.user.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author 吴金辉
 */
@Component
public class AddOrganizationCheckActivity extends BaseActivity<AddOrganizationDTO, BaseResponse> {

    @Autowired
    private UserService userService;
    @Autowired
    private OrganizationService organizationService;

    @Autowired
    private OrganizationInfoMapper organizationInfoMapper;

    @Override
    public void handler(AddOrganizationDTO request, BaseResponse response) {
        notNullCheck(request);
        businessCheck(request);
    }

    /**
     * 空校验
     *
     * @param request
     */
    private void notNullCheck(AddOrganizationDTO request) {
        Assert.notNull(request.getOrgName(), "组织名称为空");
        Assert.notNull(request.getOrgDesc(), "描述信息不能为空");
        Assert.notNull(request.getOrgLeaderId(), "组织管理员id");
    }

    private void businessCheck(AddOrganizationDTO request) {
        // 可以添加组织的用户
        UserInfoDTO userInfoDTO = userService.getUserInfoByAuthCode(request).getBody();
        IsAdminDTO isAdminDTO = userService.isSystemAdmin(userInfoDTO).getBody();
        // 组织名称不能相同
        int countByName=organizationInfoMapper.countByName(request.getOrgName());
        if(countByName>0){
            // 组织名称重复
            throw new BusinessException(ResultCode.PARAM_IS_INVALID,"组织名称重复");
        }
        // 系统管理员可以添加任意组织
        if (isAdminDTO.getIsAdmin().equals(true)) {
            return;
        }
        // 判断
        GetByIdRequest getByIdRequest = new GetByIdRequest();
        getByIdRequest.setId(request.getParentId());
        OrganizationResponse response = organizationService.getOrganizationInfo(getByIdRequest).getBody();
        Integer orgLeaderId = response.getOrgLeaderId();
        Assert.isTrue(orgLeaderId.equals(userInfoDTO.getUserId()), "该用户没有权限在" + response.getOrgName() + "下新增子组织");

    }

}
